package com.user.gamecenter.service;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.user.gamecenter.receiver.RegularlyDownloadReceiver;

import java.util.Calendar;


/**
 * @类名: RegularlyDownloadService
 * @描述: 定时下载服务
 * @作者 cms
 * @创建日期 2017/2/8 11:12
 */

public class RegularlyDownloadService extends Service {

    private static final String TAG = "RegularlyDownloadService";

    private PendingIntent pi;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @SuppressLint("LongLogTag")
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: 1-------------------------------- ");
        Intent i = new Intent(getApplicationContext(), RegularlyDownloadReceiver.class);
        pi = PendingIntent.getBroadcast(getApplicationContext(), 0, i, 0);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @SuppressLint("LongLogTag")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        long triggerAtTime;
        if (System.currentTimeMillis() > getDayBeginTwo()) {
            triggerAtTime = getTomorrowBeginTwo();
        } else {
            triggerAtTime = getDayBeginTwo();
        }

        //测试
        //triggerAtTime = System.currentTimeMillis() + 60 * 1000;
        Log.d(TAG, "1------------------pi =" + pi.toString());
        manager.set(AlarmManager.RTC_WAKEUP, triggerAtTime, pi);

        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * @方法名: 获取当天2点的时间
     * @参数：
     * @返回值：
     * @描述:
     * @作者： cms
     * @创建日期 2017/2/8 15:01
     */
    private long getDayBeginTwo() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 2);//24小时制
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 001);
        return cal.getTimeInMillis();
    }

    private long getTomorrowBeginTwo() {
        return getDayBeginTwo() + 24 * 60 * 60 * 1000;
    }

}
